package cn.myzf.douyin;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.myzf.chatapi.WeChatClient;
import cn.myzf.chatapi.wechat.entity.contact.WXContact;
import cn.myzf.chatapi.wechat.entity.contact.WXUser;
import cn.myzf.chatapi.wechat.utils.WxClientRel;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static cn.myzf.chatapi.WeChatDemo.GSON;
import static cn.myzf.chatapi.WeChatDemo.LISTENER;


/**
 * @package cn.myzf.douyin
 * @Date Created in 2019/7/25 17:13
 * @Author myzf
 */

@Service
public class DyService {

    public static  ExecutorService ex = Executors.newFixedThreadPool(4);
    static  String API[] = {
            "https://aweme.snssdk.com/aweme/v1/aweme/detail/?origin_type=link&retry_type=no_retry&iid=74655440239&device_id=57318346369&ac=wifi&channel=wandoujia&aid=1128&app_name=aweme&version_code=140&version_name=1.4.0&device_platform=android&ssmix=a&device_type=MI+8&device_brand=xiaomi&os_api=22&os_version=5.1.1&uuid=865166029463703&openudid=ec6d541a2f7350cd&manifest_version_code=140&resolution=1080*1920&dpi=1080&update_version_code=1400&as=a13520b0e9c40d9cbd&cp=064fdf579fdd07cae1&aweme_id=",
            "https://aweme.snssdk.com/aweme/v1/aweme/detail/?origin_type=link&retry_type=no_retry&iid=74655440239&device_id=57318346369&ac=wifi&channel=wandoujia&aid=1128&app_name=aweme&version_code=140&version_name=1.4.0&device_platform=android&ssmix=a&device_type=MI+8&device_brand=xiaomi&os_api=22&os_version=5.1.1&uuid=865166029463703&openudid=ec6d541a2f7350cd&manifest_version_code=140&resolution=1080*1920&dpi=1080&update_version_code=1400&as=a13510902a54ed1cad&cp=0a40dc5ba5db09cee1&aweme_id=",
            "https://aweme.snssdk.com/aweme/v1/aweme/detail/?origin_type=link&retry_type=no_retry&iid=43619087057&device_id=57318346369&ac=wifi&channel=update&aid=1128&app_name=aweme&version_code=251&version_name=2.5.1&device_platform=android&ssmix=a&device_type=MI+8&device_brand=xiaomi&language=zh&os_api=22&os_version=5.1.1&uuid=865166029463703&openudid=ec6d541a2f7350cd&manifest_version_code=251&resolution=1080*1920&dpi=480&update_version_code=2512&as=a1e500706c54fd8c8d&cp=004ad55fc8d60ac4e1&aweme_id=",
            "https://aweme.snssdk.com/aweme/v1/aweme/detail/?origin_type=link&retry_type=no_retry&iid=43619087057&device_id=57318346369&ac=wifi&channel=update&aid=1128&app_name=aweme&version_code=251&version_name=2.5.1&device_platform=android&ssmix=a&device_type=MI+8&device_brand=xiaomi&language=zh&os_api=22&os_version=5.1.1&uuid=865166029463703&openudid=ec6d541a2f7350cd&manifest_version_code=251&resolution=1080*1920&dpi=480&update_version_code=2512&as=a10500409d74bdec1d&cp=0a4ed456dedf0acee1&aweme_id=",
            "https://aweme.snssdk.com/aweme/v1/aweme/detail/?origin_type=link&retry_type=no_retry&iid=43619087057&device_id=57318346369&ac=wifi&channel=wandoujia&aid=1128&app_name=aweme&version_code=650&version_name=6.5.0&device_platform=android&ssmix=a&device_type=xiaomi+8&device_brand=xiaomi&language=zh&os_api=22&os_version=5.1.1&openudid=2e5c5ff4ce710faf&manifest_version_code=660&resolution=1080*1920&dpi=480&update_version_code=6602&mcc_mnc=46000&js_sdk_version=1.16.2.7&as=a1257080aec45ddcad&cp=0b4cd25fe4d00ccfe1&aweme_id=",
            "https://aweme.snssdk.com/aweme/v1/aweme/detail/?origin_type=link&retry_type=no_retry&iid=75364831157&device_id=68299559251&ac=wifi&channel=wandoujia&aid=1128&app_name=aweme&version_code=650&version_name=6.5.0&device_platform=android&ssmix=a&device_type=xiaomi+8&device_brand=xiaomi&language=zh&os_api=22&os_version=5.1.1&openudid=2e5c5ff4ce710faf&manifest_version_code=660&resolution=1080*1920&dpi=480&update_version_code=6602&mcc_mnc=46000&js_sdk_version=1.16.2.7&as=a125a0b01f946d2cdd&cp=0744d553ffd60cc3e1&aweme_id=",
            "https://aweme.snssdk.com/aweme/v1/aweme/detail/?retry_type=no_retry&iid=74655440239&device_id=57318346369&ac=wifi&channel=wandoujia&aid=1128&app_name=aweme&version_code=140&version_name=1.4.0&device_platform=android&ssmix=a&device_type=MI+8&device_brand=xiaomi&os_api=22&os_version=5.1.1&uuid=865166029463703&openudid=ec6d541a2f7350cd&manifest_version_code=140&resolution=1080*1920&dpi=1080&update_version_code=1400&as=a125372f1c487cb50f&cp=728dcc5bc7f4f558e1&aweme_id="
    };




    public String[]  getRealUrl(String adUrl,WXUser ww) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        String url = "";
        String url2 = "";
        String s = UUID.randomUUID().toString();

        try {
                url2 = decodeHttpUrl(adUrl);
                Document doc = null;
                //先请求接口

//                String body = HttpRequest.get("https://lyfzn.top/plugins/douyin/videoPrase/parseByLink.php?url=" + url2).execute().body();
//                JsonParser j = new JsonParser();
//                JsonObject jj = j.parse(body).getAsJsonObject();
//
//                JsonArray urls = jj.get("urls").getAsJsonArray();
//                if(urls.size()>0){
//                    if(StringUtils.isNotEmpty(urls.get(0).toString())){
//                        OkHttpClient client = new OkHttpClient();
//                        Request request = new Request.Builder()
//                                .url(urls.get(0).toString().replaceAll("\"", ""))
//                                .get().addHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android 5.0; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
//                                .build();
//                        Response response = client.newCall(request).execute();
//                        String s = UUID.randomUUID().toString();
//
//                        return new String[]{url2,"http://cc.douzi.com/"+s+".mp4"};
//
//                    }
//                }
//


                try {
                    doc = Jsoup.connect(url2).cookie("cookie", "tt_webid=6711334817457341965; _ga=GA1.2.611157811.1562604418; _gid=GA1.2.1578330356.1562604418; _ba=BA0.2-20190709-51")
                            //模拟手机浏览器
                            .header("user-agent", "Mozilla/5.0 (Linux; U; Android 5.0; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
                            //.header("cookie","tt_webid=6711334817457341965; _ga=GA1.2.611157811.1562604418; _gid=GA1.2.1578330356.1562604418; _ba=BA0.2-20190709-51")
                            .timeout(12138).get();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 解析网页标签
                Elements elem = doc.getElementsByTag("script");
                String url1 = elem.toString();
                int startLen = url1.indexOf("itemId: \"");
                int endLen = url1.indexOf("\",\n" +
                        "            test_group");
                String itemId = url1.substring(startLen, endLen).replaceAll("itemId: \"", "");
                /**
                 * API里面有7个网站，可以自己选择，
                 * 最后一个是出问题的
                 * 最后一个是出问题的
                 * 最后一个是出问题的
                 */
                String result2 = HttpRequest.get(API[4] + itemId + "&ts=" + System.currentTimeMillis() + "&_rticket=" + System.currentTimeMillis())
                        //模拟手机浏览器
                        .header(Header.USER_AGENT, "Mozilla/5.0 (Linux; U; Android 5.0; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")//头信息，多个头信息多次调用此方法即可
                        .timeout(12138)//超时，毫秒
                        .execute().body();
                try {
                    //GOSN解析
                    JsonParser jsonParser = new JsonParser();
                    JsonObject jsonObject = jsonParser.parse(result2).getAsJsonObject();
                    JsonArray asJsonArray = jsonObject.get("aweme_detail").getAsJsonObject().get("video").getAsJsonObject().get("play_addr").getAsJsonObject().get("url_list").getAsJsonArray();
                     url = asJsonArray.get(2).toString().replaceAll("\"", "");
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .get().addHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android 5.0; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
                            .build();
                    Response response = client.newCall(request).execute();
                    String filePath = "c:/video/"+s+".mp4";
                        File outputFile = new File(filePath);
                        outputFile.setWritable(true, false);
                        FileOutputStream outputFileStream = null;
                        outputFileStream = new FileOutputStream(outputFile);
                        ResponseBody body1 = response.body();
                       // FileUtils.copyInputStreamToFile(body1.byteStream(), outputFile);
                        IOUtils.write(body1.bytes(),outputFileStream);
                        //为模拟微信客户端设置监听器
                        WeChatClient weChatClient = (WeChatClient) WxClientRel.get("myzf");
                        HashMap<String, WXUser> stringWXUserHashMap = weChatClient.userFriends();
                        String id ="";
                        Collection<WXUser> values = stringWXUserHashMap.values();
                        if(ww!=null){
                          id = ww.id;
                        }
                        WXContact contact = weChatClient.userContact(id);
                           if (contact != null) {
                               System.out.println("success:" + GSON.toJson(weChatClient.sendFile(contact, outputFile)));

                           } else {
                               System.out.println("联系人未找到");
                           }

                    url = response.request().url().toString();
                    int start = url.indexOf("http");
                    int end = url.lastIndexOf("?");
                    url = url.substring(start, end);
                    if (!StringUtils.isEmpty(url)) {
                        System.out.println("解析地址为:" + url);
                       // FileUtils.copyInputStreamToFile(response.body().byteStream(), new File(Thread.currentThread().getContextClassLoader().getResource("")+"video/"+"1.mp4"));
                    }
                } catch (Exception e) {
                    System.out.println("解析失败，请更换地址重试,报错信息：" + e.getMessage());
                    getRealUrl(adUrl,null);

                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

        }
        return new String[]{url2,"http://cc.douzi.com/"+s+".mp4"};

    }


    private static String decodeHttpUrl(String url) {
        // 检测是否有中文，如果没有中文就是直接地址
        boolean containChinese = isContainChinese(url);
        if (containChinese) {
            int start = url.indexOf("http");
            int end = url.lastIndexOf("/");
            String decodeurl = url.substring(start, end);
            return decodeurl;
        } else
            return url;
    }


    private static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    public static String getDownloadUrl(String url) {
        String url2 = decodeHttpUrl(url);
        Document doc = null;
        try {
            doc = Jsoup.connect(url2).cookie("cookie", "tt_webid=6711334817457341965; _ga=GA1.2.611157811.1562604418; _gid=GA1.2.1578330356.1562604418; _ba=BA0.2-20190709-51")
                    //模拟手机浏览器
                    .header("user-agent", "Mozilla/5.0 (Linux; U; Android 5.0; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
                    //.header("cookie","tt_webid=6711334817457341965; _ga=GA1.2.611157811.1562604418; _gid=GA1.2.1578330356.1562604418; _ba=BA0.2-20190709-51")
                    .timeout(12138).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解析网页标签
        Elements elem = doc.getElementsByTag("script");
        String url1 = elem.toString();
        int startLen = url1.indexOf("itemId: \"");
        int endLen = url1.indexOf("\",\n" +
                "            test_group");
        String itemId = url1.substring(startLen, endLen).replaceAll("itemId: \"", "");
        /**
         * API里面有7个网站，可以自己选择，
         * 最后一个是出问题的
         * 最后一个是出问题的
         * 最后一个是出问题的
         */
        String result2 = HttpRequest.get(API[4] + itemId + "&ts=" + System.currentTimeMillis() + "&_rticket=" + System.currentTimeMillis() + 182)
                //模拟手机浏览器
                .header(Header.USER_AGENT, "Mozilla/5.0 (Linux; U; Android 5.0; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")//头信息，多个头信息多次调用此方法即可
                .timeout(12138)//超时，毫秒
                .execute().body();
        try {
            //GOSN解析
            JsonParser jsonParser = new JsonParser();
            JsonObject jsonObject = jsonParser.parse(result2).getAsJsonObject();
            JsonArray asJsonArray = jsonObject.get("aweme_detail").getAsJsonObject().get("video").getAsJsonObject().get("play_addr").getAsJsonObject().get("url_list").getAsJsonArray();
            url = asJsonArray.get(2).toString().replaceAll("\"", "");
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .get().addHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android 5.0; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
                    .build();
            Response response = client.newCall(request).execute();
            url = response.request().url().toString();
            int start = url.indexOf("http");
            int end = url.lastIndexOf("?");
            url = url.substring(start, end);
            return url;
        } catch (Exception e) {
            return e.getMessage();
        }
    }


    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));

    }






}
